﻿using System.Collections.Generic;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;

namespace DarkSky.Microdata.Settings {
    public class MicrodataPartSettingsEvents : ContentDefinitionEditorEventsBase {
        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition) {
            if(definition.PartDefinition.Name != "MicrodataPart")
                yield break;

            var settings = definition.Settings.GetModel<MicrodataPartSettings>();

            if (!settings.Entries.Any()) {
                settings.Entries.Add(new MicrodataEntry { Key = "name", Value = "{Content.DisplayText}" });
                settings.Entries.Add(new MicrodataEntry { Key = "url", Value = "{Content.DisplayUrl}" });
                settings.Entries.Add(new MicrodataEntry { Key = "image", Value = "{MediaPickerField.Url}" });
                settings.Entries.Add(new MicrodataEntry { Key = "author", Value = "{Content.Author}" });
                settings.Entries.Add(new MicrodataEntry { Key = "description", Value = "{Content.Summary}" });
                settings.Entries.Add(new MicrodataEntry { Key = "datePublished", Value = "{Content.Date}" });
                settings.Entries.Add(new MicrodataEntry { Key = "dateModified", Value = "{Content.Modified}" });
                settings.Entries.Add(new MicrodataEntry { Key = "interactionCount", Value = "{Content.Comments}" });
            }

            // Add an empty entry to allow the user to add a new entry
            settings.Entries.Add(new MicrodataEntry());

            yield return DefinitionTemplate(settings);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel) {
            if (builder.Name != "MicrodataPart")
                yield break;

            var settings = new MicrodataPartSettings {
                Entries = new List<MicrodataEntry>()
            };

            if(updateModel.TryUpdateModel(settings, "MicrodataPartSettings", null, null)) {
                var entries = settings.Entries.ToList();
                entries.RemoveAll(x => string.IsNullOrWhiteSpace(x.Key) && string.IsNullOrWhiteSpace(x.Value));

                settings.Entries = entries;
                settings.Build(builder);
            }

            yield return DefinitionTemplate(settings);
        }
    }
}